<script setup>
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { useUserStore } from "@/stores/user";
import { getProductDetailAPI } from '@/api/Goods.js';
import { getAddressAPI,createTradeAPI } from '@/api/Trade.js';
import { ElMessage } from 'element-plus';

// 获取路由中的 productId 参数
const route = useRoute();
const productId =  route.query.productId;

// 从 store 中获取当前用户的 ID
const store = useUserStore();
const userId = store.UserId;

// 定义响应式变量
const product = ref({});
const addressList = ref([]);
const selectedAddressId = ref(null);
const quantity = ref(1);

// 在 setup 中直接执行异步函数获取数据
const fetchData = async () => {
  const { data } = await getProductDetailAPI(productId);
  product.value = data.data;

  const addressResponse = await getAddressAPI(userId);
  addressList.value = addressResponse.data.data;
};

// 调用数据加载函数
fetchData();

// 提交订单处理函数
// 提交订单处理函数
const submitOrder = async () => {
  const orderData = {
    buyerId: userId,
    sellerId: product.value.userId,
    goodsId: product.value.id,
    goodsName: product.value.name,
    price: product.value.price,
    nums: quantity.value,
    mailAddressId: selectedAddressId.value,
    isConfirm: 0,
    image: product.value.image,
    type:product.value.type
  };

  try {
    const { data } = await createTradeAPI(orderData);
    console.log(data.code);

    if (data.code === 200) {
      ElMessage.success('订单提交成功，请耐心等待卖家发货');
    } else if (data.code === 400) {
      // 弹出确认框询问用户是否继续购买
      await ElMessageBox.confirm(
          '已经购买过该商品，是否继续购买？',
          '确认再次购买',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      );

      // 用户确认后，重新设置 isConfirm 为 1 并提交订单
      const confirmOrderData = { ...orderData, isConfirm: 1 };
      const { data: confirmData } = await createTradeAPI(confirmOrderData);

      if (confirmData.code === 200) {
        ElMessage.success('订单提交成功，请耐心等待卖家发货');
      } else {
        ElMessage.info(confirmData.msg);
      }
    } else {
      ElMessage.info(data.msg);
    }
  } catch (error) {
    ElMessage.info('操作已取消');
  }
};
</script>


<template>
  <div class="buy-page">
    <h1 style="text-align: center;">购买商品</h1>

    <el-table v-if="product" :data="[product]" style="width: 1000px;margin-top: 20px;">
      <el-table-column label="图片" width="100">
        <template #default="scope">
          <img style="width:100px;height:100px ;" :src="scope.row.image" alt="商品图片" class="product-image" />
        </template>
      </el-table-column>
      <el-table-column label="商品名称" width="100">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="商品描述" width="200" style="font-size: 14px;"  >
        <template #default="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="破损率" width="100">
        <template #default="scope">
          {{ scope.row.brokenRate }}
        </template>
      </el-table-column>
      <el-table-column label="价格" width="100">
        <template #default="scope">
          {{ (scope.row.price * quantity).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="购买数量">
        <template #default="scope">
          <el-input-number
              v-model="quantity"
              :min="1"
              :max="product.nums"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="可用库存">
        <template #default="scope">
          {{ product.nums }}
        </template>
      </el-table-column>

    </el-table>

    <!-- 地址选择 -->
    <el-card v-if="addressList.length" class="address-card">
      <h3>选择收货地址</h3>
      <el-radio-group style="height:  200px;display:grid" v-model="selectedAddressId">
        <el-radio
            v-for="address in addressList"
            :key="address.id"
            :label="address.id"
        >
          {{ address.addressee }} - {{ address.addresseePhone }}
          <br />
          {{ address.address }}
        </el-radio>
      </el-radio-group>
    </el-card>

    <!-- 提交订单按钮 -->
    <el-button
        type="primary"
        :disabled="!selectedAddressId"
        @click="submitOrder"
        style="margin-left:92%"
    >
      提交订单
    </el-button>
  </div>
</template>



<style scoped>
.buy-page {

  margin-top: -150px;
}
.product-card {
  margin-bottom: 20px;
}
.product-image {
  width: 100%;
  height: 300px;
  object-fit: cover;
  margin-bottom: 10px;
}
.address-card {
  margin-top: 20px;
  margin-bottom: 20px;


}
</style>
